<?php


namespace App\HttpController\Api;


use App\HttpController\Base;
use App\Utility\Assert\AssertException;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use EasySwoole\Validate\Validate;

class ApiBase extends Base
{

    function onRequest(?string $action): ?bool
    {
        $response = $this->response();
        $request = $this->request();
        // TODO: Implement onRequest() method.
        $response->withHeader('Access-Control-Allow-Origin', '*');
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        if ($request->getMethod() === 'OPTIONS') {
            $response->withStatus(Status::CODE_OK);
            return false;
        }
        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }

    protected function getRequestAndCookieParam($name){
        $value = $this->request()->getRequestParam($name);
        if (empty($value)) {
            $value = $this->request()->getCookieParams($name);
        }
        return $value;
    }

    function onException(\Throwable $throwable): void
    {
        if ($throwable instanceof ParamValidateError) {
            /** @var Validate $validate */
            $validate = $throwable->getValidate();
            $errorMsg = $validate->getError()->getErrorRuleMsg();
            $this->writeJson(Status::CODE_BAD_REQUEST, null, $errorMsg);
        } else if ($throwable instanceof AssertException) {
            $this->writeJson(Status::CODE_BAD_REQUEST, $throwable->getErrorCode(), $throwable->getMessage());
        } else {
//            var_dump((string)$throwable);
            $this->writeJson(Status::CODE_INTERNAL_SERVER_ERROR, null, $throwable->getMessage());
        }
    }


}
